<!-- src/views/dashboard/index.vue -->
<template>
  <div style="width: 90%;margin: auto; display: flex;justify-content: center;">
    <!-- 侧边菜单栏 -->
    <div style="margin-top: 20px ;">
      <SideMenu :menuList="menuList" @update:menuList="updateMenu" />
    </div>

    <div class="dashboard">
      <!-- Hero Section with Great Wall background -->
      <div class="hero-section">
        <div class="hero-content">
          <h1 class="hero-title">取之于民</h1>
          <h1 class="hero-title">用之于民</h1>
          <div class="hero-badge">AI智慧税务实训平台</div>
        </div>
      </div>

      <!-- Main Content Area -->
      <div class="dashboard-content">
        <!-- Companies Section -->
        <div class="companies-section">
          <h3 class="section-title">
            <el-icon>
              <Document />
            </el-icon>
            所有案例
          </h3>

          <div v-loading="loading" class="companies-list">
            <div v-for="company in companies" :key="company.id" class="company-item" @click="selectCompany(company)">
              <el-checkbox v-model="company.selected" @change="handleCompanySelection(company)" />
              <span class="company-name">{{ company.name }}</span>
              <el-button type="primary" size="small">
                进入
              </el-button>
            </div>
          </div>

          <!-- Pagination -->
          <div class="pagination-section">
            <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="totalCompanies"
              layout="prev, pager, next" :pager-count="5" @current-change="handlePageChange" />
          </div>
        </div>

        <!-- System Entry Section -->
        <div class="system-entry-section">
          <h3 class="section-title">
            系统入口 <span class="subtitle">(根据案例设置开放入口)</span>
          </h3>

          <div v-loading="systemModulesLoading" class="system-entries">
            <div v-for="entry in systemModules" :key="entry.id" class="entry-item"
              :class="{ 'disabled': !entry.is_used }">
              <div class="entry-indicator" :class="{ 'active': entry.is_used }"></div>
              <span class="entry-name">{{ entry.name }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Module Selection Dialog -->
      <ModuleSelectionDialog v-model="showModuleDialog" :selected-company="selectedCompany"
        @practice-started="handlePracticeStarted" />
    </div>
  </div>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { dashboardService } from '@/api/dashboard'
import ModuleSelectionDialog from './ModuleSelectionDialog.vue'
import SideMenu from '@/components/SideMenu/SideMenu.vue'

const router = useRouter()

const menuList = ref([
  { title: '首页概览', active: true, router: '/' },
  { title: '实训任务', active: false, router: '/' },
  { title: '案例库', active: false, router: '/' },
  { title: '资源库', active: false, router: '/' },
  { title: '实训成绩', active: false, router: '/' },
  { title: 'AI解析', active: false, router: '/' },
  { title: '模拟考试', active: false, router: '/' },
  { title: '竞赛活动', active: false, router: '/' }
])

const updateMenu = (newList) => {
  menuList.value = newList
}

// Loading states
const loading = ref(false)
const systemModulesLoading = ref(false)

// Dialog state
const showModuleDialog = ref(false)
const selectedCompany = ref(null)

// Pagination
const currentPage = ref(1)
const pageSize = ref(10)
const totalCompanies = ref(0)

// Data
const companies = ref([])
const systemModules = ref([])
const currentCompanyModules = ref([])

// API调用
const fetchCompanies = async () => {
  try {
    loading.value = true
    const response = await dashboardService.company.getAll()
    companies.value = response.data.map(company => ({
      ...company,
      selected: false
    }))
    totalCompanies.value = response.data.length

    // 默认选中第一个公司
    if (companies.value.length > 0) {
      companies.value[0].selected = true
      await fetchCompanyModules(companies.value[0].id)
    }
  } catch (error) {
    console.error('获取公司列表失败:', error)
    ElMessage.error('获取公司列表失败，请重试')
  } finally {
    loading.value = false
  }
}

const fetchSystemModules = async () => {
  try {
    systemModulesLoading.value = true
    const response = await dashboardService.systemModule.getAll()
    systemModules.value = response.data
  } catch (error) {
    console.error('获取系统模块失败:', error)
    ElMessage.error('获取系统模块失败，请重试')
  } finally {
    systemModulesLoading.value = false
  }
}

// 获取特定公司的模块
const fetchCompanyModules = async (companyId) => {
  try {
    const response = await dashboardService.company.getModules(companyId)
    // 确保模块数据包含 is_used 属性
    currentCompanyModules.value = response.data.map(module => ({
      ...module,
      is_used: module.is_used !== undefined ? module.is_used : true
    }))
    updateSystemModulesDisplay()
  } catch (error) {
    console.error('获取公司模块失败:', error)
    currentCompanyModules.value = []
    updateSystemModulesDisplay()
  }
}

// 更新系统模块显示状态
const updateSystemModulesDisplay = () => {
  const enabledModuleNames = new Set(currentCompanyModules.value.map(m => m.name))

  systemModules.value = systemModules.value.map(module => ({
    ...module,
    is_used: enabledModuleNames.has(module.name)
  }))
}

const handlePageChange = (page) => {
  currentPage.value = page
  // 如果需要服务端分页，在这里调用API
}

// 处理公司选择变化
const handleCompanySelection = async (company) => {
  // 取消其他公司的选中状态
  companies.value.forEach(c => c.selected = false)
  // 选中当前公司
  company.selected = true

  // 获取该公司的模块
  await fetchCompanyModules(company.id)
}

const selectCompany = (company) => {
  selectedCompany.value = company
  showModuleDialog.value = true
}

const handlePracticeStarted = (practice) => {
  // 获取路由路径
  const routePath = dashboardService.navigation.getRouteByModuleName(practice.module.name)

  // 检查模块是否已实现
  if (dashboardService.navigation.isModuleImplemented(practice.module.name)) {
    ElMessage.success(`开始练习：${practice.company.name} - ${practice.module.name}`)
    router.push(routePath)
  } else {
    ElMessage.info(`${practice.module.name} 功能开发中`)
  }
}

// 初始化数据
onMounted(async () => {
  // 先获取系统模块列表
  await fetchSystemModules()
  // 再获取公司列表（会自动选中第一个公司并获取其模块）
  await fetchCompanies()
})
</script>

<style scoped>
.dashboard {
  position: relative;
  min-height: calc(100vh - 140px);
  width: 80%;
}

/* Hero Section */
.hero-section {
  height: 400px;
  background-image: url('@/assets/background.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin: 20px 20px;
}

.hero-content {
  text-align: center;
  color: white;
  z-index: 2;
}

.hero-title {
  font-size: 48px;
  font-weight: bold;
  margin: 0 0 10px 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.hero-badge {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.9);
  color: #4A90E2;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
}

/* Dashboard Content */
.dashboard-content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 30px;
  padding: 0 20px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
}

.subtitle {
  font-size: 12px;
  color: #666;
  font-weight: normal;
}

/* Companies Section */
.companies-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.companies-list {
  margin-bottom: 20px;
  min-height: 200px;
}

.company-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 4px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.company-item:hover {
  background-color: #f0f2f5;
}

.company-item:last-child {
  border-bottom: none;
}

.company-name {
  flex: 1;
  color: #333;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

/* System Entry Section */
.system-entry-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.system-entries {
  margin-bottom: 20px;
  min-height: 150px;
}

.entry-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  font-size: 14px;
}

.entry-item.disabled {
  color: #999;
}

.entry-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ddd;
}

.entry-indicator.active {
  background: #4A90E2;
}

.entry-name {
  flex: 1;
}

/* Responsive */
@media (max-width: 768px) {
  .dashboard-content {
    grid-template-columns: 1fr;
  }

  .hero-title {
    font-size: 32px;
  }
}
</style>